import 'dart:async';

import 'package:flutter/widgets.dart';

abstract class StatefulWloc<S, P extends StatefulWidget> extends State<P> {
  final _stateController = StreamController<S>.broadcast();
  S? _state;

  Stream<S> get stream => _stateController.stream;

  S get initialState;

  S get state {
    _state ??= initialState;
    return _state!;
  }

  void emit(S state) {
    if (_state != state) {
      _state = state;
      _stateController.add(state);
    }
  }

  @override
  @mustCallSuper
  void dispose() {
    super.dispose();
    _stateController.close();
  }
}
